#include "tcpserver.h"
#include "ui_tcpserver.h"
#include "database.h"
#include "protocolmessage.h"
#include "zhidebug.h"
#include <QMessageBox>

TcpServer::TcpServer(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::TcpServer)
{
    ui->setupUi(this);
    this->resize(300,300);
    this->setWindowTitle(tr("QtCMS服务器"));

    contentListWidget = new QListWidget;

    portLabel = new QLabel(tr("端 口:"), this);
    portLineEdit = new QLineEdit(this);
    portLineEdit->setText(tr("8000"));

    btn_start_server = new QPushButton(tr("开启服务器"));

    QWidget *mainWidget = new QWidget(this);
    mainLayout = new QGridLayout(mainWidget);
    mainLayout->addWidget(contentListWidget, 0, 0, 1, 2);
    mainLayout->addWidget(portLabel, 1, 0);
    mainLayout->addWidget(portLineEdit, 1, 1);
    mainLayout->addWidget(btn_start_server, 2, 0, 1, 2);

    this->setCentralWidget(mainWidget);

    connect(btn_start_server, SIGNAL(clicked()), this, SLOT(btn_start_server_clicked()));

}

TcpServer::~TcpServer()
{
    delete ui;
}

void TcpServer::startService()
{
    this->tcpServer=new QTcpServer(this);
    this->tcpSocket=new QTcpSocket(this);

    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(acceptConnection()));
    connect(tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),
                     this,SLOT(displayError(QAbstractSocket::SocketError)));

    db = new Database(Database::MYSQL);
}

void TcpServer::stopService()
{
    this->tcpServer=nullptr;
    this->tcpSocket=nullptr;

    db->close();
    db = nullptr;
}


void TcpServer::receiveData()
{

    QString receviveData = tcpSocket->readAll();
    ZhiDebug::Info("Receive data from client! data:" + receviveData);
    ProtocolMessage *msg = new ProtocolMessage(receviveData);
    qDebug() << msg;
    if(msg->category == ProtocolMessage::VALIDATA)
    {
        ZhiDebug::Info("Received data from client is validata!");

        if(msg->data.contains("username") && msg->data.contains("password")){
            ZhiDebug::Info("Received data's format is right!");
            //TODO VALIDATA
            QHash<QString, QString>data;
            QString responseData;
            if(db->validataUser(msg->data.value("username"), msg->data.value("password")))
            {
                data.insert("result", "true");
                data.insert("message", "Success to login!");
                ProtocolMessage *protocolMessage = new ProtocolMessage(ProtocolMessage::VALIDATA, data);
                responseData = protocolMessage->toMessage();
            }else{
                data.insert("result", "false");
                data.insert("message", "Failed to login!");
                ProtocolMessage *protocolMessage = new ProtocolMessage(ProtocolMessage::VALIDATA, data);
                responseData = protocolMessage->toMessage();

            }
            ZhiDebug::Info("Send data:" + responseData);
            tcpSocket->write(responseData.toLatin1());
        }
    }



}

void TcpServer::btn_start_server_clicked()
{
    if(this->isStarted){
        tcpSocket->close();
        tcpServer->close();
        stopService();
        btn_start_server->setText(tr("开启服务器"));
        this->isStarted = false;
    }else{
        startService();
        QString port = portLineEdit->text().trimmed();
        if(port.isEmpty()){
            QMessageBox::information(this, tr("Info"), tr("The port is null"), QMessageBox::Ok);
            return;
        }
        if(!tcpServer->listen(QHostAddress::Any, port.toUShort()))
        {
            qDebug()<<tcpServer->errorString();
            return;
        }

        btn_start_server->setText(tr("关闭服务器"));

        this->isStarted = true;
    }




}


void TcpServer::acceptConnection()
{
    tcpSocket=tcpServer->nextPendingConnection();
    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(receiveData()));   //**********
}

void TcpServer::displayError(QAbstractSocket::SocketError)
{
    qDebug()<<tcpSocket->errorString();
    tcpSocket->close();
}
